# -- encoding:utf-8 --
import pickle
import re
import tensorflow as tf
from model import Model
from utils import get_logger
from utils import load_config
from data_utils import input_from_line
import openpyxl

flags = tf.app.flags
flags.DEFINE_string("log_file", "./log/train.log", "File for log")
flags.DEFINE_string("map_file", "./config/maps.pkl", "file for maps")
flags.DEFINE_string("ckpt_path", "./ckpt/bilstm", "Path to save model")
flags.DEFINE_string("config_file", "./config/config_file", "File for config")
FLAGS = tf.app.flags.FLAGS
# 日志工具(记录操作日志)
logger = get_logger(FLAGS.log_file)

CN_NUM = {
    u'〇': 0,
    u'一': 1,
    u'二': 2,
    u'三': 3,
    u'四': 4,
    u'五': 5,
    u'六': 6,
    u'七': 7,
    u'八': 8,
    u'九': 9,

    u'零': 0,
    u'壹': 1,
    u'贰': 2,
    u'叁': 3,
    u'肆': 4,
    u'伍': 5,
    u'陆': 6,
    u'柒': 7,
    u'捌': 8,
    u'玖': 9,

    u'貮': 2,
    u'两': 2,
}
CN_UNIT = {
    u'十': 10,
    u'拾': 10,
    u'百': 100,
    u'佰': 100,
    u'千': 1000,
    u'仟': 1000,
    u'万': 10000,
    u'萬': 10000,
    u'亿': 100000000,
    u'億': 100000000,
    u'兆': 1000000000000,
}

def cn2dig(cn):
    lcn = list(cn)
    unit = 0  # 当前的单位
    ldig = []  # 临时数组
    while lcn:
        cndig = lcn.pop()
        if cndig in CN_UNIT:
            unit = CN_UNIT.get(cndig)
            if unit == 10000:
                ldig.append('w')  # 标示万位
                unit = 1
            elif unit == 100000000:
                ldig.append('y')  # 标示亿位
                unit = 1
            elif unit == 1000000000000:  # 标示兆位
                ldig.append('z')
                unit = 1
            continue
        else:
            dig = CN_NUM.get(cndig)
            if unit and dig:
                dig = dig * unit
                unit = 0
            else:
                dig = 0
                unit = 0
            ldig.append(dig)
    if unit == 10:  # 处理10-19的数字
        ldig.append(10)
    ret = 0
    tmp = 0
    while ldig:
        x = ldig.pop()
        if x == 'w':
            tmp *= 10000
            ret += tmp
            tmp = 0
        elif x == 'y':
            tmp *= 100000000
            ret += tmp
            tmp = 0
        elif x == 'z':
            tmp *= 1000000000000
            ret += tmp
            tmp = 0
        elif x == None:
            x = 0
            tmp += x
        else:
            tmp += x
    ret += tmp
    return ret

def predict(line):
    config = load_config(FLAGS.config_file)
    tf_config = tf.ConfigProto()
    tf_config.allow_soft_placement = True
    tf_config.gpu_options.allow_growth = True
    with open(FLAGS.map_file, "rb") as f:
        char_to_id, id_to_char, tag_to_id, id_to_tag = pickle.load(f)
    with tf.Session(config=tf_config) as sess:
        model = Model(config)
        # 模型恢复
        sess.run(tf.global_variables_initializer())
        ckpt = tf.train.get_checkpoint_state(FLAGS.ckpt_path)
        if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
            model.saver.restore(sess, ckpt.model_checkpoint_path)
            if line.strip():
                line = re.compile(' ').sub('', line)  # 去掉中间空格
                result = model.evaluate_line(sess, input_from_line(line, char_to_id), id_to_tag)
                return result
            else:
                return 4001

def xlsx_run(xlsx_name, sheet_name):
    rb = openpyxl.load_workbook(xlsx_name)
    sheet = rb.get_sheet_by_name(sheet_name)
    row = 2  # 开始行
    while row <= 20:  # 结束行
        text = sheet['E' + str(row)].value
        tf.reset_default_graph()  # 重新创建图
        result_list = predict(text)  # 预测
        print(result_list)

        dqm_list = []
        lc_list = []
        zmj_list = []
        zj_list = []
        bz_list = []
        yzm_list = []
        pnu_list = []
        entitles = result_list['entities']
        for entitle in entitles:
            if entitle['type'] == 'DQM':
                dqm_list.append(entitle['word'])

            if entitle['type'] == 'LC':
                if entitle['word'].isdecimal():
                    lc_list.append(str(entitle['word']))
                else:
                    cn_to_dig = cn2dig(entitle['word'])
                    if cn_to_dig:
                        lc_list.append(str(cn_to_dig))

            if entitle['type'] == 'ZMJ':
                if entitle['word'].isdecimal():
                    zmj_list.append(str(entitle['word']))
                else:
                    cn_to_dig = cn2dig(entitle['word'])
                    if cn_to_dig:
                        zmj_list.append(str(cn_to_dig))

            if entitle['type'] == 'ZJ':
                if entitle['word'].isdecimal():
                    zj_list.append(str(entitle['word']))
                else:
                    cn_to_dig = cn2dig(entitle['word'])
                    if cn_to_dig:
                        zj_list.append(str(cn_to_dig))

            if entitle['type'] == 'BZ':
                bz_list.append(str(entitle['word']))
            if entitle['type'] == 'YZM':
                yzm_list.append(entitle['word'])
            if entitle['type'] == 'PNU':
                pnu_list.append(entitle['word'])

        # 地区
        if dqm_list != []:
            dqm = dqm_list[0]
            sheet['D' + str(row)] = str(dqm)
        # 楼层
        if lc_list != []:
            lc = '、'.join(set(lc_list))
            sheet['F' + str(row)] = str(lc)
        # 面积
        if zmj_list != []:
            if len(zmj_list) > 1:
                zmj_list = [int(x) for x in zmj_list]
                minmj = min(zmj_list)
                if '共' in text:
                    zmj = ''
                else:
                    zmj = sum(zmj_list)
            else:
                minmj = zmj_list[0]
                zmj = zmj_list[0]
            sheet['G' + str(row)] = str(minmj)
            sheet['H' + str(row)] = str(zmj)
        # 租金
        if zj_list != []:
            if len(zj_list) > 1:
                k_list = []
                zj_list = [int(x) for x in zj_list]
                for k, v in enumerate(zj_list):
                    if v < 6:
                        k_list.append(k)
                if k_list == []:
                    zj_list = [str(x) for x in zj_list]
                    zj = '、'.join(set(zj_list))
                else:
                    for key in k_list:
                        new_zj = zj_list[key-1] + zj_list[key]
                        zj_list.pop(key-1)
                        zj_list.pop(key-1)
                        zj_list.insert(key-1, new_zj)
                    zj_list = [str(x) for x in zj_list]
                    zj = '、'.join(set(zj_list))
            else:
                zj = zj_list[0]
            sheet['I' + str(row)] = str(zj)
        # 备注
        if bz_list != []:
            bz = '、'.join(set(bz_list))
            sheet['J' + str(row)] = str(bz)
        # 业主姓名
        if yzm_list != []:
            yzm = yzm_list[0]
            sheet['K' + str(row)] = str(yzm)
        # 业主电话
        if pnu_list != []:
            pnu = pnu_list[0]
            sheet['L' + str(row)] = str(pnu)

        # 保存到excel
        rb.save(xlsx_name)

        row += 1

    print('------------{} 解析完成------------'.format(xlsx_name))

if __name__ == "__main__":
    xlsx_list = [
        # './building_data/盘源测试数据表-lstm.xlsx',
        # './building_data/福永三盘源8.16-lstm.xlsx',
        # './building_data/福永三新盘8.1-lstm.xlsx',
        # './building_data/福永三新盘8.8-lstm.xlsx',
        # './building_data/盘源数据表-lstm.xlsx',
        # './building_data/福永三盘源表8.24-lstm.xlsx',
        # './building_data/福永新盘2020.9.1-lstm.xlsx',
        './building_data/福永三新盘9.5-lstm.xlsx',
    ]
    for name in xlsx_list:
        xlsx_name = name
        sheet_name = 'Sheet1'

        xlsx_run(xlsx_name, sheet_name)



